// pages/luckDraw/luckDrawIndex.js
import stepTestData from "../testData/stepData";
var mfApi = require('../../api/api.js');

const app = getApp();
Page({

        /**
         * 页面的初始数据
         */
        data: {
                baseUrl: app.globalData.baseUrl,
                currentCard: 0,

                // 是否显示抽奖结果弹窗
                isShowLuckResultFrame: false,
                // 是否获奖
                isLuckGet: false,
                // 是否显示提示框
                isShotTip: false,
                // 获奖奖品id
                awardId: null,

                cardData: [],

                // 印迹数据
                stampData: stepTestData,

                isFellowShow: false,
                // -1 加载中  1 成功  0 失败
                isOfficialLoadStatus: -1,
                isFellowed: false,

                // tab
                isFixedTop: false, //是否固定顶部
                currentTar: -1, // 当前标签tab
                navbarInitTop: 0, //导航栏初始化距顶部的距离

                // 外部分享来的奖品id
                inUserAwardId: null,

                // 是否显示stamp tip
                isShowStampTip: false,
                // 点选的stamp
                selectedStampIndex: 0,
                // stamp tip 位置

        },

        onShareTimeline:function(){
 
        },
        /**
         * 生命周期函数--监听页面加载
         */
        onLoad: function (options) {
                this.setData({
                        top: app.menu.top,
                        h: app.menu.height
                })

                wx.createSelectorQuery().select('#navbar').boundingClientRect().exec((rect) => {
                        console.log("===rect====", rect)
                        if (rect && rect[0].top > 0) {
                                var navbarInitTop = parseInt(rect[0].top);
                                console.log("navbarInitTop", navbarInitTop);
                                this.setData({
                                        navbarInitTop: navbarInitTop - 67
                                });
                        }
                });

                if (options && options.inUserAwardId) {
                        this.setData({
                                inUserAwardId: options.inUserAwardId,
                        })
                }
        },

        onPageScroll(e) {
                // var that = this;
                // debugger
                // this.hideStampTipView();
                var scrollTop = parseInt(e.scrollTop); //滚动条距离顶部高度
                // console.log("scrollTop", scrollTop);
                if(scrollTop <= 200) {
                        this.setData({
                                currentTar: 0
                        })
                }
                if (scrollTop > 200 && scrollTop <= 300) {
                        this.setData({
                                currentTar: 0
                        })
                } else if (scrollTop > 300 && scrollTop < 800) {
                        this.setData({
                                currentTar: 1
                        })
                } else if (scrollTop > 800) {
                        this.setData({
                                currentTar: 2
                        })
                }

                //判断'滚动条'滚动的距离 和 '元素在初始时'距顶部的距离进行判断
                var isSatisfy = scrollTop >= this.data.navbarInitTop ? true : false;
                //为了防止不停的setData, 这儿做了一个等式判断。 只有处于吸顶的临界值才会不相等
                if (this.data.isFixedTop === isSatisfy) {
                        return false;
                }
                this.setData({
                        isFixedTop: isSatisfy
                });
        },

        selectGiftScroll(e) {
                let {
                        index
                } = e.currentTarget.dataset;
                console.log("index", index);
                switch (index) {
                        case 0:
                                this.goScroll(290)
                                break;
                        case 1:
                                this.goScroll(749)
                                break;
                        case 2:
                                this.goScroll(1080)
                }
                app.saveTrack(`抽奖中心-tab${index + 1}`);
        },

        goScroll(offset) {
                wx.pageScrollTo({
                        scrollTop: offset,
                        duration: 500
                })
        },

        onShow() {

                setTimeout(() => {
                        this.checkUser();
                        this.getAwardListApi();

                        if (this.data.inUserAwardId) {
                                this.getGivenPrizeApi()
                        }
                }, 0);

        },

        onSwiperChange(e) {
                let {
                        current
                } = e.detail
                this.setData({
                        currentCard: current
                })
        },

        onResultFrameCloseClick() {
                this.setData({
                        isShowLuckResultFrame: false,
                })
                this.onShow();
        },

        async getAwardListApi() {
                let res = await mfApi.http(
                        mfApi.getAwardList(app.globalData.openId), "GET", {});
                if (res.code != 200)
                        return;

                let tempList = res.result.myAwardList;
                res.result.giveAwardList.forEach(e => {
                        e.isGiveAward = true
                })
                tempList = tempList.concat(res.result.giveAwardList)
                // cardData
                this.setData({
                        cardData: JSON.parse(JSON.stringify(tempList)) 
                })

                if (this.data.isShowLuckResultFrame) {
                        let temp =  this.data.cardData[this.data.currentCard]

                        if( Number(temp.userAwardStatus) == 4 || Number(temp.userAwardStatus) == 5) {
                                this.setData({
                                        isShowLuckResultFrame: false
                                })
                        }
                }
        },

        async checkUser() {
                let res = await mfApi.http(
                        mfApi.getRoomList(app.globalData.openId), "GET", {});
                if (res.code != 200)
                        return;

                let tempStampData = this.data.stampData;
                tempStampData.forEach(element => {
                        // element.index
                        let roomInfo = res.result.roomList.find(e => {
                                return e.roomNo == element.index;
                        });
                        if (roomInfo)
                                element.markFlag = roomInfo.markFlag;
                })

                let indexData = tempStampData.find(e => {
                        return e.index == 6
                })

                indexData.markFlag = res.result.shareVideoMarkFlag

                this.setData({
                        stampData: tempStampData
                });

                let userRes = await mfApi.http(
                        mfApi.getUserInfo(app.globalData.openId), "POST", {});

                if (userRes.code != 200)
                        return;

                this.setData({
                        isFellowed: userRes.result.attentionFlag == "1"
                })
        },

        async onFellowClick() {
                if(this.data.isFellowed) 
                        return;
                // this.setData({
                //         isFellowShow: true,
                //         isOfficialLoadStatus: -1,
                // })
                await mfApi.http(
                        mfApi.attentionWx(app.globalData.openId), "POST", {});
                
                wx.navigateTo({
                  url: '/pages/webViewPage/webViewPage',
                })
        },

        async toLuckDraw(e) {
                wx.showLoading({
                        title: "加载中",
                });
                app.saveTrack(`luckdraw-开礼盒${e.detail}`);
                let res = await mfApi.http(mfApi.draw(app.globalData.openId, e.detail), "POST", {});
                console.log(res);

                await this.getAwardListApi();
                wx.hideLoading();
                if (
                        res.result.awardId == null ||
                        res.result.awardId.length == 0
                ) {
                        this.setData({
                                isShotTip: true
                        })
                } else {
                        this.setData({
                                isShowLuckResultFrame: true,
                        })
                }
        },

        async getGivenPrizeApi() {
                let res = await mfApi.http(mfApi.getGivenPrize(app.globalData.openId, this.data.inUserAwardId), "POST", {});
                console.log(res);

                if (res.code != 200) {
                        wx.showToast({
                                title: res.message,
                                icon: "none"
                                
                        })
                        this.setData({
                                inUserAwardId: null,
                        })
                        return;
                }

                await this.getAwardListApi();

                let tempindex = this.data.cardData.findIndex(e => {
                        return e.userAwardId == this.data.inUserAwardId
                });

                this.setData({
                        currentCard: tempindex,
                        inUserAwardId: null,
                        isShowLuckResultFrame: true,
                })
        },

        async givePrizeApi() {
                let res = await mfApi.http(mfApi.givePrize(app.globalData.openId, this.data.cardData[this.data.currentCard].userAwardId), "POST", {});
                return res;
        },

        /**
         * 显示抽奖弹框
         */
        toShowLuckDraw() {
                this.setData({
                        isShowLuckResultFrame: true,
                })
        },

        /**
         * 关注组件加载成功
         */
        onOfficialLoadOk() {
                this.setData({
                        isOfficialLoadStatus: 1,
                })
                console.log("onOfficialLoadOk --- isOfficialLoadStatus === " + this.data.isOfficialLoadStatus)
        },

        /**
         * 关注组件加载失败
         */
        onOfficialLoadError(err) {
                console.log("onOfficialLoadError -=-=-=-=090909")
                console.log(err)
                this.setData({
                        isOfficialLoadStatus: 0,
                })
                console.log("onOfficialLoadError --- isOfficialLoadStatus === " + this.data.isOfficialLoadStatus)
        },

        async onFellowTipBtnCloseClick() {
                this.setData({
                        isFellowShow: false,
                })
                console.log("isOfficialLoadStatus === " + this.data.isOfficialLoadStatus)
                
                await mfApi.http(
                        mfApi.attentionWx(app.globalData.openId), "POST", {});
                
                app.saveTrack(`抽奖中心-即刻关注`);
                this.onShow();
        },

        goBack() {
                wx.navigateBack();
        },

        async onShareAppMessage(object) {
                if(object.from == "menu") {
                        return {
                                title: 'LA MER邀你一同参展，探寻属于你的自愈空间',
                                path: `/pages/index/index?inChannel=commonShare`,
                                imageUrl: "https://morefun-active-1.oss-cn-shanghai.aliyuncs.com/2022_lamer_cream_show/share/wx-share.jpg",
                        }
                }

                let res = await this.givePrizeApi();
                if (res.code != 200) {
                        wx.showToast({
                                title: res.message,
                                icon: "none"
                        })
                        return;
                }
                app.saveTrack(`抽奖中心-转赠`);
                return {
                        title: 'LA MER邀你一同参展，探寻属于你的自愈空间',
                        path: `/pages/index/index?toPage=giveLuckDraw&userAwardId=${this.data.cardData[this.data.currentCard].userAwardId}`,
                        imageUrl: "https://morefun-active-1.oss-cn-shanghai.aliyuncs.com/2022_lamer_cream_show/share/wx-share.jpg",
                        // promise
                        success: () => {
                                console.log(" share ok")
                        },
                        fail: () => {
                                console.log(" share fail")
                        }
                }
        },

        onTryClick() {
                app.saveTrack(`抽奖中心-申请试用`);
                wx.navigateToMiniProgram({
                        appId: 'wx548a7b5fc4aae274',
                        path: 'orderPage/pages/order2204/index',
                        success(res) {
                                // 打开成功
                        }
                })
        },

        /**
         * 提示弹窗点击业务按钮
         */
        onTipBtnClick() {
                wx.navigateBack();
                this.setData({
                        isShotTip: false
                })
        },

        onTipBtnCloseClick() {
                this.setData({
                        isShotTip: false
                })
        },

        goToHome() {
                app.saveTrack(`抽奖中心-返回首页`);
                wx.navigateBack();
        },

        goToMall() {
                app.saveTrack(`抽奖中心-去商城`);
                wx.navigateToMiniProgram({
                        appId: 'wxb6bd8b23ea3f3dcc',
                        path: 'pages/home/home?mtj_lkid=12163&chan_id=581',
                        success(res) {
                                // 打开成功
                        }
                })
        },

        /**
         * 点击stamp icon的事件
         */
        onStampIconClick(e) {
                console.log("onStampIconClick --- ", e.currentTarget.dataset.index)
                let tempindex = e.currentTarget.dataset.index;
                if(this.data.selectedStampIndex == tempindex) {
                        this.hideStampTipView();
                        return;
                }

                this.setData({
                        isShowStampTip: true,
                        selectedStampIndex: e.currentTarget.dataset.index,
                })
        },

        hideStampTipView() {
                if(!this.data.isShowStampTip)
                        return;
                this.setData({
                        isShowStampTip: false,
                })
        }
})